package com.heihei.getvideowidth;

import com.heihei.util.FileUtilF;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


public class GetVideoWidthStart {
    public static void main(String[] args) throws IOException {
//        startHandleDirVideo(new File("E:\\BaiduNetdiskDownload\\抖音反差婊百万粉丝coser美女 小扑通 最全视频福利合集【83V530P2G\\v - 剪辑专用"));
//        FileUtilF.handleFiles(new File("E:\\BaiduNetdiskDownload\\图包合集"), file -> {
//            file.renameTo(new File(file.getParent(), file.getName().trim()));
//        });
        start();
    }

    public static void start() {
        System.out.println("请输入源目录：");
        File validSrcDir = FileUtilF.getValidSrcDir();
        startHandleDirVideo(validSrcDir);
    }

    private static void startHandleDirVideo(File parentDir) {
        for (File videoFile : parentDir.listFiles()) {
            if(FileUtilF.isVideo(videoFile)) {
                FFmpegFrameGrabber frameGrabber = null;
                try {
                    frameGrabber = FFmpegFrameGrabber.createDefault(videoFile);
                    frameGrabber.start();
                    Frame frame = frameGrabber.grabImage();
                    Java2DFrameConverter converter = new Java2DFrameConverter();
                    BufferedImage image = converter.getBufferedImage(frame);
                    int width = image.getWidth();
                    int height = image.getHeight();
                    String screenType = width >= height ? "横屏" : "竖屏";
                    String currDirStr = screenType + "_" + width + "_" + height;
                    File targetDir = new File(parentDir, currDirStr);
                    if(!targetDir.exists()) {
                        targetDir.mkdirs();
                    }
                    if (frameGrabber != null) {
                        try {
                            frameGrabber.stop();
                        } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
                        }
                    }
                    videoFile.renameTo(new File(targetDir, videoFile.getName()));
                } catch (FrameGrabber.Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    if (frameGrabber != null) {
                        try {
                            frameGrabber.stop();
                        } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
                        }
                    }
                }

            }
        }
    }
}
